package com.tbit.uqbike.webmanager.handler;

import com.tbit.uqbike.webmanager.util.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jing
 * @date 2020/10/2813:55
 * @Description:
 */
@Component
@Aspect
public class MapAspect {
    /**
     * @param
     * @return void
     * @Description: 切点，对有Test注解的类进行拦截
     * @createDate 2020/10/27 19:49
     */
    @Pointcut("@annotation(com.tbit.uqbike.annos.EncapsulateMap)")
    public void controllerAspect() {

    }

    @Around("controllerAspect()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Map<String, Object> params = new HashMap<>();
        Map<String, Object> data = new HashMap<>();
        String start = null;
        /**获取连接点的方法签名对象*/
        Signature sign = joinPoint.getSignature();
        if (!(sign instanceof MethodSignature)) {
            throw new RuntimeException("该注解只支持方法");
        }
        /**转换成方法签名*/
        MethodSignature methodSignature = (MethodSignature) sign;
        /**获取方法的参数类型*/
        Class<?>[] parameterTypes = methodSignature.getMethod().getParameterTypes();
        /**获取方法参数名*/
        String[] parameterNames = methodSignature.getParameterNames();
        /**获取连接点方法运行时的入参列表*/
        Object[] args = joinPoint.getArgs();
        for (int i = 0; i < parameterTypes.length; i++) {
            if (args[i] instanceof Map) {
                params = (Map<String, Object>) args[i];
            } else if (args[i] instanceof Long) {
                data.put(parameterNames[i], new Date((Long) args[i]));
            } else {
                if ("pageNO".equals(parameterNames[i]) || "start".equals(parameterNames[i])) {
                    start = "start";
                    parameterNames[i] = "start";
                }
                data.put(parameterNames[i], args[i]);
            }
        }
        if (StringUtils.isNotNull(start)) {
            data.put(start, ((int) data.get("rowCount")) * ((int) data.get(start) - 1));
        }
        params.putAll(data);
        return joinPoint.proceed();
    }
}
